package com.wolfking.service.ssoauth.service;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wolfking.back.core.bean.Role;
import com.wolfking.back.core.mybatis.BaseService;
import com.wolfking.service.ssoauth.mapper.RoleMapper;
import com.wolfking.service.ssoauth.mapper.RoleMenuRelationMapper;
import com.wolfking.service.ssoauth.relation.RoleMenuRelation;

/**
 * 角色的service
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年5月13日 下午9:29:15
 * @copyright wolfking
 */
@Service
public class RoleService extends BaseService<RoleMapper, Role> {

	@Autowired
	private RoleMenuRelationMapper roleMenuRelationMapper;

	@Override
	@Transactional
	public boolean add(Role role) {
		if (StringUtils.isEmpty(role.getId()))
			role.setId(UUID.randomUUID().toString().replace("-", ""));
		mapper.insert(role);
		List<RoleMenuRelation> relations = RoleMenuRelation.assemblyRoles(role);
		for (RoleMenuRelation roleMenuRelation : relations)
			roleMenuRelationMapper.insert(roleMenuRelation);
		return true;
	}

	@Override
	@Transactional
	public boolean update(Role role) {
		RoleMenuRelation relation = new RoleMenuRelation();
		relation.setRoleId(role.getId());
		roleMenuRelationMapper.deleteAccuracy(relation);
		mapper.update(role);
		List<RoleMenuRelation> relations = RoleMenuRelation.assemblyRoles(role);
		for (RoleMenuRelation roleMenuRelation : relations)
			roleMenuRelationMapper.insert(roleMenuRelation);
		return true;
	}

	@Override
	@Transactional
	public boolean deleteById(Object id) {
		Role role = new Role();
		role.setId(String.valueOf(id));
		mapper.deleteById(role);
		RoleMenuRelation relation = new RoleMenuRelation();
		relation.setRoleId(role.getId());
		roleMenuRelationMapper.deleteAccuracy(relation);
		return true;
	}

	@Override
	public Role getById(Object id) {
		Role role = new Role();
		role.setId(String.valueOf(id));
		role = mapper.getById(role);
		RoleMenuRelation relation = new RoleMenuRelation();
		relation.setRoleId(role.getId());
		List<RoleMenuRelation> list = roleMenuRelationMapper.seleteAccuracy(relation);
		String menuIds = "";
		if (list != null)
			for (RoleMenuRelation roleMenuRelation : list)
				menuIds += roleMenuRelation.getMenuId() + ",";
		if (menuIds.length() > 0)
			menuIds = menuIds.substring(0, menuIds.length() - 1);
		role.setMenuIds(menuIds);
		return role;
	}

}
